/**
 * @author Matthew.He
 */
package com.iot.ic.modules.dao.impl;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.iot.ic.modules.dao.BackendDao;
import com.iot.ic.modules.model.User;
import com.iot.ic.modules.util.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.iot.ic.modules.model.Pager;

/**
 * @author Matthew.He
 *
 */
@Service("BackendDao")
public class BackendDaoImpl implements BackendDao {

	@Autowired
	private org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean entityManagerFactory;

	private EntityManager getEntiyManager() {
		return this.entityManagerFactory.getNativeEntityManagerFactory().createEntityManager();
	}

	@Override
	public Object addOrUpdateObject(Object o) throws Exception {
		EntityManager em = getEntiyManager();
		em.getTransaction().begin();

		try {
			Method method = o.getClass().getMethod("getId", null);
			if (method.invoke(o) == null) {
				em.persist(o);
			}
			o = em.merge(o);
			em.getTransaction().commit();

		} catch (Exception e) {
			e.printStackTrace();
			em.getTransaction().rollback();
			throw new RuntimeException(e.getMessage());
		} finally {
			em.close();
		}

		return o;
		// this.entityManagerFactory.getCurrentSession().saveOrUpdate(o);
	}

	@Override
	public Object getObjectByClaz(Class clz, Serializable key) throws Exception {
		// return this.entityManagerFactory.getCurrentSession().get(clz, key) ;
		EntityManager em = getEntiyManager();

		Object o = em.find(clz, key);
		em.close();
		return o;
	}

	public List<User> queryUser(Map map) throws Exception {
		EntityManager em = getEntiyManager();
		StringBuffer hql = new StringBuffer();
		hql.append(" select u.* from User u where 1=1	");
		String name = RequestUtil.getValue(map, "userName");
		if (!StringUtils.isEmpty(name)) {
			hql.append(" and u.name like '%").append(name).append("%'");
		}
		String sex = RequestUtil.getValue(map, "sex");
		if (!StringUtils.isEmpty(sex)) {
			hql.append(" and u.sex ='").append(sex).append("'");
		}
		hql.append(" order by u.cre_Dt desc ");
		Query jquery = em.createNativeQuery(hql.toString(), User.class);
		List totalList = jquery.getResultList();
		Pager pager = (Pager) RequestUtil.getObjValue(map, "pager");
		pager.setTotal(totalList == null ? 0 : totalList.size());
		jquery.setFirstResult(pager.getFirstResult());
		jquery.setMaxResults(pager.getPageSize());
		List list = jquery.getResultList();
		em.close();
		return list;
	}

	public org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean getEntityManagerFactory() {
		return entityManagerFactory;
	}

	public void setEntityManagerFactory(
			org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean entityManagerFactory) {
		this.entityManagerFactory = entityManagerFactory;
	}

	@Override
	public void deleObject(Object o) throws Exception {
		if (o == null) {
			return;
		}
		EntityManager em = this.getEntiyManager();
		em.getTransaction().begin();

		try {
			o = em.merge(o);
			em.remove(o);
			em.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			em.getTransaction().rollback();
			throw new RuntimeException(e.getMessage());
		} finally {
			em.close();
		}
	}

	public List<User> queryDepart(Map<String, String> requestMap) throws Exception {
		EntityManager em = this.getEntiyManager();

		StringBuffer sql = new StringBuffer();
		sql.append(" select t.* from Department t where 1=1");

		String departName = requestMap.get("departName");
		if (!StringUtils.isEmpty(departName)) {
			sql.append(" and t.name like '%").append(departName).append("%'");
		}

		Query jquery = em.createNativeQuery(sql.toString(), User.class);
		List list = jquery.getResultList();
		em.close();
		return list;
	}

	public User getUserbyName(String userName) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append(" select t.* from User t where t.name=?1");
		EntityManager em = this.getEntiyManager();

		Query query = em.createNativeQuery(sql.toString(), User.class);
		query.setParameter(1, userName);

		List list = query.getResultList();

		Object outO;
		if (list == null || list.size() != 1) {
			outO = null;
		} else {
			outO = list.get(0);
		}

		em.close();
		return (User) outO;
	}

	public List<User> queryUser11(Map queryMap) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append(" select t.* from User t where 1=1");

		String UserName = RequestUtil.getValue(queryMap, "UserName");
		if (!StringUtils.isEmpty(UserName)) {
			sql.append(" and t.name like '%").append(UserName).append("'");
		}

		EntityManager em = this.getEntiyManager();
		Query query = em.createNativeQuery(sql.toString(), User.class);

		List list = query.getResultList();
		em.close();

		return list;
	}

	public List<User> queryUser1(Map queryMap) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append(" select t.* from User t where 1=1");
		String UserName = RequestUtil.getValue(queryMap, "UserName");
		if (!StringUtils.isEmpty(UserName)) {
			sql.append(" and t.loc like '%").append(UserName).append("'");
		}
		EntityManager em = this.getEntiyManager();
		Query query = em.createNativeQuery(sql.toString(), User.class);
		List list = query.getResultList();
		em.close();
		return list;
	}

	public List<User> queryUser2(Map queryMap) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append(" select t.* from User t where 1=1");

		String UserName = RequestUtil.getValue(queryMap, "UserName");
		if (!StringUtils.isEmpty(UserName)) {
			sql.append(" and t.name like '%").append(UserName).append("%'");
		}

		EntityManager em = this.getEntiyManager();
		Query query = em.createNativeQuery(sql.toString(), User.class);

		List list = query.getResultList();
		em.close();

		return list;
	}

	@Deprecated
	public List<User> queryUser3(Map queryMap) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append(" select t.* from User t where 1=1");
		String UserId = RequestUtil.getValue(queryMap, "UserId");
		if (!StringUtils.isEmpty(UserId)) {
			sql.append(" and t.User_id=").append(UserId);
		}
		String unUserId = RequestUtil.getValue(queryMap, "unUserId");
		if (!StringUtils.isEmpty(unUserId)) {
			sql.append(" and (t.User_id is null or t.User_id!=").append(unUserId).append(")");
		}
		String hadUserId = RequestUtil.getValue(queryMap, "hadUserId");
		if (!StringUtils.isEmpty(hadUserId)) {
			if ("false".equals(hadUserId)) {
				sql.append(" and t.User_id is null ");
			} else if ("true".equals(hadUserId)) {
				sql.append(" and t.User_id is not null ");
			}
		}

		String UserIds = RequestUtil.getValue(queryMap, "UserIds");
		if (!StringUtils.isEmpty(UserIds)) {
			sql.append(" and t.User_id in (").append(UserIds).append(")");
		}

		EntityManager em = this.getEntiyManager();
		Query query = em.createNativeQuery(sql.toString(), User.class);
		List list = query.getResultList();
		em.close();
		return list;
	}

	@Deprecated
	public List<User> queryEquip(Map queryMap) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append(" select t.* from equipment t where 1=1");
		String UserId = RequestUtil.getValue(queryMap, "UserId");
		if (!StringUtils.isEmpty(UserId)) {
			sql.append(" and t.User_id=").append(UserId);
		}
		sql.append(" order by t.User_id,t.equip_type");
		EntityManager em = this.getEntiyManager();
		Query query = em.createNativeQuery(sql.toString(), User.class);
		List list = query.getResultList();
		em.close();
		return list;
	}

	  @Deprecated
	public User queryPicture(String UserId) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append(" select t.* from picture t where 1=1");

		if (!StringUtils.isEmpty(UserId)) {
			sql.append(" and t.User_id=").append(UserId);
		}

		EntityManager em = this.getEntiyManager();
		Query query = em.createNativeQuery(sql.toString(), User.class);

		  User one = (User) query.getResultList().stream().findFirst().orElse(null);
		em.close();
		return one;
	}

	 
	public List<User> queryUserWithPermission(Map queryMap) throws Exception {
		StringBuffer sql = new StringBuffer();

		sql.append("select t.* from User t where 1=1");
		sql.append(" and ");

		String UserUnHad = RequestUtil.getValue(queryMap, "UserUnHad");
		if (!StringUtils.isEmpty(UserUnHad)) {
			sql.append(" NOT EXISTS (select 1 from permissions p where p.User_id = t.id and p.User_id=")
					.append(UserUnHad).append(" ) ");
		}

		String UserHad = RequestUtil.getValue(queryMap, "UserHad");
		if (!StringUtils.isEmpty(UserHad)) {
			sql.append(" EXISTS (select 1 from permissions p where p.User_id = t.id and p.User_id=").append(UserHad)
					.append(" ) ");
		}

		EntityManager em = this.getEntiyManager();
		Query query = em.createNativeQuery(sql.toString(), User.class);

		List list = query.getResultList();
		em.close();
		return list;
	}

	public List<User> queryDeptUser(Map queryMap) throws Exception {
		StringBuffer sql = new StringBuffer();

		sql.append("select t.* from User t where 1=1");
		sql.append(" and ");

		String deptUnHad = RequestUtil.getValue(queryMap, "deptUnHad");
		if (!StringUtils.isEmpty(deptUnHad)) {
			sql.append(" NOT EXISTS (select 1 from dept_User p where p.User_id = t.id and p.dept_id=").append(deptUnHad)
					.append(" ) ");
		}

		String deptHad = RequestUtil.getValue(queryMap, "deptHad");
		if (!StringUtils.isEmpty(deptHad)) {
			sql.append(" EXISTS (select 1 from dept_User p where p.User_id = t.id and p.dept_id=").append(deptHad)
					.append(" ) ");
		}

		EntityManager em = this.getEntiyManager();
		Query query = em.createNativeQuery(sql.toString(), User.class);

		List list = query.getResultList();
		em.close();
		return list;
	}

	public void cleanPermissionsByUserId(int id) {
		StringBuffer sql = new StringBuffer();
		sql.append(" delete from permissions  where User_id=").append(id);

		EntityManager em = this.getEntiyManager();
		em.getTransaction().begin();

		try {
			Query query = em.createNativeQuery(sql.toString());
			query.executeUpdate();

			em.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			em.getTransaction().rollback();
		} finally {
			em.close();
		}
	}

	 
	public void cleanDeptUserByDeptId(int id) {
		StringBuffer sql = new StringBuffer();
		sql.append(" delete from dept_User  where dept_id=").append(id);
		EntityManager em = this.getEntiyManager();
		em.getTransaction().begin();
		try {
			Query query = em.createNativeQuery(sql.toString());
			query.executeUpdate();
			em.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			em.getTransaction().rollback();
		} finally {
			em.close();
		}
	}
	public void cleanDeptUserByUserId(int id) {
		StringBuffer sql = new StringBuffer();
		sql.append(" delete from dept_User  where User_id=").append(id);
		EntityManager em = this.getEntiyManager();
		em.getTransaction().begin();
		try {
			Query query = em.createNativeQuery(sql.toString());
			query.executeUpdate();
			em.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			em.getTransaction().rollback();
		} finally {
			em.close();
		}
	}

	public List<User> querySceneByName(String userName) {
		StringBuffer sql = new StringBuffer();
		sql.append(" select t.* from scene t where 1=1 ");
		if (!StringUtils.isEmpty(userName)) {
			sql.append(" and t.name='").append(userName).append("'");
		}
		EntityManager em = this.getEntiyManager();
		Query query = em.createNativeQuery(sql.toString(), User.class);

		List list = query.getResultList();
		em.close();
		return list;
	}

	public String getUserByUserName(String userName) {
		StringBuffer sql = new StringBuffer();
		sql.append(" select t.* from User t where t.name=?1");
		EntityManager em = this.getEntiyManager();
		Query query = em.createNativeQuery(sql.toString(), User.class);
		query.setParameter(1, userName);
		List list = query.getResultList();
		Object outO;
		if (list == null || list.size() != 1) {
			outO = null;
		} else {
			outO = list.get(0);
		}
		em.close();
		return ((User) outO).getUserName();
	}

	public String queryUserIds(Map queryMap) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("select group_concat(id) from User");

		EntityManager em = this.getEntiyManager();
		Query query = em.createNativeQuery(sql.toString());

		String result = (String) query.getSingleResult();
		em.close();

		return result;
	}

	public List<User> queryUserNames() throws Exception {
		String sql = "select t.id, t.name from User t where 1=1";

		EntityManager em = this.getEntiyManager();
		Query query = em.createNativeQuery(sql);

		List list = query.getResultList();
		em.close();

		return list;
	}
	
	
	public List<User>  getUserbyOtherId(Map<String,Object> map) throws Exception {
		StringBuffer sql = new StringBuffer();
		List<User> list = null;
		if(map.containsKey("deptId")){
			String deptId = map.get("deptId").toString();
			sql.append(" select t.* from User t where t.depart_id="+deptId);
		}else if(map.containsKey("UserId")){
			String UserId = map.get("UserId").toString();
			sql.append(" select t.* from User t where t.User_id="+UserId);
		}
		EntityManager em = this.getEntiyManager();
		Query query = em.createNativeQuery(sql.toString(), User.class);
		list = query.getResultList();
		em.close();
		return list;
	}

}
